package scalaLearning.scalaBasic.ch14implicit2

/**
  * 隐式参数
  *再增加需求，如果希望4/5两边的《》自定义样式呢？
  */

import scala.language.implicitConversions
import scala.math._

class Fraction2(n: Int, d: Int) {
  private val num: Int = if (d == 0) 1 else n * sign(d) / gcd(n, d)
  private val den: Int = if (d == 0) 0 else d * sign(d) / gcd(n, d)
  override def toString = num + "/" + den
  def sign(a: Int) = if (a > 0) 1 else if (a < 0) -1 else 0
  def gcd(a: Int, b: Int): Int = if (b == 0) abs(a) else gcd(b, a % b)

  def *(other: Fraction2) = new Fraction2(num * other.num, den * other.den)
}

object Fraction2 {
  def apply(n: Int, d: Int) = new Fraction2(n, d)
}


/**
  * 这里以上就是在不修改类的情况下，给类增加新的功能
  * @param fraction
  */
//class  BeautifyFraction1(fraction:Fraction){
//  def beautify1 = "<<"+fraction+">>"
//}
//
//object  BeautifyFraction1{
//  implicit def fraction2BeautifyFraction1(fraction: Fraction) = new BeautifyFraction1(fraction)
//}
//
//import  BeautifyFraction1._

/**
  * 再增加需求，如果希望4/5两边的《》自定义样式呢？
  */
case class Delimiteres(left:String,right:String)
//                                            隐式参数
class  BeautifyFraction2(fraction:Fraction2)(implicit delimiteres: Delimiteres){
  def beautify = delimiteres.left + " " + fraction + " " + delimiteres.right
}

object  BeautifyFraction2{
//  implicit def fraction2BeautifyFraction(fraction: Fraction2) = new BeautifyFraction2(fraction)
}

//import  BeautifyFraction2._


object Main extends App {
//  implicit def int2Fraction(n: Int) = Fraction(n, 1)
//  val result = 3 * Fraction(4, 5) // Calls int2Fraction(3)
//  println(result)

//  println(Fraction(4,5)*Fraction(3,5))
//  println(Fraction(4,5).beautify1)

  /**
    * 自定义样式
    */
  implicit val delimiteres = new Delimiteres("<--","-->")

  implicit def fraction2BeautifyFraction(fraction: Fraction2) = new BeautifyFraction2(fraction)
  println(Fraction2(4,5).beautify)

}
